<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>


    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" type="index" align="center" prop="id" width="80"/>
      <el-table-column label="订单编号" align="center" prop="orderNo" show-overflow-tooltip="" />
      <el-table-column label="商品名称" align="center" prop="skuName" />
      <el-table-column label="订单状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="order_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="订单金额" align="center" prop="amount" >
        <template #default="scope">
          <span>{{ scope.row.amount/100 }}</span>
        </template>
      </el-table-column> 
      <el-table-column label="订单时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary"  @click="handleUpdate(scope.row)" v-hasPermi="['manage:order:query']">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看详情对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
  <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
    <el-form-item label="订单编号" prop="orderNo">
      {{ form.orderNo }}
    </el-form-item>
    <el-form-item label="商品名称" prop="skuName">
      {{ form.skuName }}
    </el-form-item>
    <el-form-item label="订单金额" prop="amount">
      {{ form.amount }}
    </el-form-item>
    <el-form-item label="订单状态" prop="status">
      <template #default="scope">
          <dict-tag :options="order_status" :value="form.status"/>
      </template>
    </el-form-item>
    <el-form-item label="设备编号" prop="innerCode">
      {{ form.innerCode }}
    </el-form-item>
    <el-form-item label="设备地址" prop="addr">
      {{ form.addr }}
    </el-form-item>
    <el-form-item label="创建时间" prop="createTime">
      {{parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
    </el-form-item>
    <el-form-item label="完成时间" prop="createTime">
      {{ parseTime(form.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
    </el-form-item>
    <el-form-item label="支付方式" prop="payType" v-show="form.status == 1">
      {{form.payType === 'wxpay' ? '微信支付' : form.payType === 'alipay' ? '支付宝支付' : '未知'}}
    </el-form-item>
    <el-form-item label="交易单号" prop="tradeNo" v-show="form.status == 1">
      {{ form.tradeNo }}
    </el-form-item>
    <el-form-item label="操作" prop="finishUser" v-show="form.status == 1|| form.status == 0"> 
      <div v-if="form.status == 0"> 
        <el-button  @click="closeOrder(form.orderNo,form.payType)" v-hasPermi="['manage:order:close']">关闭订单</el-button>
      </div>
      <div v-if="form.status == 1">
          <el-button @click="Refund(form.orderNo,form.payType)" v-hasPermi="['manage:order:refund']">退款</el-button>
      </div>
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </template>
</el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder, delOrder, addOrder, updateOrder } from "@/api/manage/order";
import mqtt from 'mqtt';
const { proxy } = getCurrentInstance();
const { order_status } = proxy.useDict('order_status');
import { ElMessage } from 'element-plus';
const orderList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    createTime: null,
  },
  rules: {
  },
  mqtt:{
     client: null,
    isConnected: false,
    topic: '',
    message: ''
  }
});

const { queryParams, form, rules } = toRefs(data);
var client = mqtt.connect('ws://192.168.88.2/mqtt', {
  port: 8083,
  clientId: 'OrderInfoShow',
  username: 'admin',
  password: 'public',
  clean: true
})

client.on('connect', function () {
  console.log('连接成功:')
  
  // 订阅支付成功主题
  client.subscribe('server/dkd', { qos:2 }, (error) => {
    if (!error) {
      console.log('主题订阅成功')
    } else {
      console.log('主题订阅失败', error)
    }
  })
})

client.on('message', (topic, message) => {
  //console.log('收到消息:', topic, message.toString())
  
  // 根据不同的主题处理消息
  if (topic === 'dkd/server') {
    // 解析消息内容，如果为true则关闭弹窗
      const result = JSON.parse(message.toString())
      console.log(result)
      if (result.data.code === 200) {
        ElMessage.success(result.data.data)
      }
  }
})



/** 查询订单列表 */
function getList() {
  loading.value = true;
  listOrder(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    orderList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}


/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}


/** 查看详情操作 */
function handleUpdate(row) {
  const _id = row.id || ids.value
  getOrder(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "订单详情";
  });
}

/** 关闭订单 */
function closeOrder(orderNo, platform) {
  fetch('/pay-api/order/closeOrder/'+orderNo+'/'+platform, {
  method: 'GET',
  }).then(response => {
    if (response.ok === true) {
      ElMessage.success("关闭成功,请手动刷新页面");
      open.value = false;
    }else{
      ElMessage.error("关闭失败,请手动刷新页面");
    }
})
getList();
}
/** 退款 */
function Refund(orderNo, platform) {
  fetch('/pay-api/order/refund/'+orderNo+'/'+platform, {
  method: 'GET',
  }).then(response => {
    if (response.ok === true) {
      ElMessage.success("退款成功,请手动刷新页面");
      open.value = false;
    }else{
      ElMessage.error("退款失败,请手动刷新页面");
    }
})
getList();
}

getList();
</script>
